<template>
  <!--折线图-->
    <div style="width: 100%;height: 100%;" ref="chart"></div>
</template>

<script>
import * as echarts from "echarts";
import request from "@/utils/request";

export default {
    name: "lineChart",
    data() {
        return {
            dateX: [],
            dateY: [],
            chart: null // 添加 chart 属性
        };
    },
    mounted() {
        this.getData();
        window.addEventListener("resize", this.resizeChart); // 绑定 resizeChart 方法
    },
    methods: {
        async getData() {
            const { data: res } = await request.get("/views/borrowCountByWeek");
            let i = 0;
            Object.keys(res).forEach((key) => {
                let x = [];
                let y = [];
                y = res[key];
                x = key;
                this.dateX[i] = x;
                this.dateY[i] = y;
                i++;
            });
            this.echartsInit();
        },
        echartsInit() {
            let dateX = [];
            dateX = this.dateX;
            let dateY = [];
            dateY = this.dateY;
            this.chart = echarts.init(this.$refs.chart); // 初始化 ECharts 实例
            this.chart.setOption({
                title: {
                    text: "一周阅读人数",
                    textStyle: {
                        //文字颜色
                        color: "#fff"
                    }
                },
                xAxis: {
                    type: "category",
                    boundaryGap: false,
                    data: dateX
                },
                yAxis: {
                    type: "value"
                },
                series: [
                    {
                        data: dateY,
                        type: "line",
                        areaStyle: {}
                    }
                ],
                responsive: true // 启用响应式布局
            });
        },
        resizeChart() {
            this.chart.resize(); // 更新图表的大小
        }
    }
};
</script>

<style scoped></style>
